package com.idbk.chargestation.adapter;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.api.APIForPoint;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonReply;
import com.idbk.chargestation.bean.JsonReplyResult;
import com.idbk.chargestation.dialog.DialogReplyComment;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GsonUtils;

import java.util.List;

public class PointCommentReplyAdapter extends BaseAdapter {

	private Context mContext;

	/**
	 * 最初评论的评论id
	 */
	private int mCommentId;

	private List<JsonReply> mData;
	
	private StringRequest mRequest;
	
	private ProgressDialog mDialog;
	
	private OnDeleteListener mOnDeleteListener;
	
	private OnAddListener mOnAddListener;

	 PointCommentReplyAdapter(Context context, int commentId, List<JsonReply> data){
		mContext = context;

		mCommentId = commentId;

		mData = data;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mData.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mData.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	private class Holder{
		LinearLayout mLayout;
		TextView mTextReply;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;
		Holder hold;
		if(convertView == null) {
			v = LayoutInflater.from(mContext).inflate(R.layout.item_comment_reply, parent, false);
			hold = new Holder();
			hold.mLayout = (LinearLayout)v;
			hold.mTextReply = (TextView)v.findViewById(R.id.textview_reply);
			v.setTag(hold);
		} else {
			v = convertView;
			hold = (Holder)v.getTag();
		}

		bindView(position,hold);

		return v;
	}

	private void bindView(final int position,Holder hold){
		final JsonReply item = mData.get(position);
		if(item.specialFlag){
			String msg = String.format(STR_1, item.getFromUserName(), item.reply);
			hold.mTextReply.setText(Html.fromHtml(msg));
		} else {
			String msg = String.format(STR_2, item.getFromUserName(), item.getToUserName(), item.reply);
			hold.mTextReply.setText(Html.fromHtml(msg));
		}

		//短按
		hold.mLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				//如果该回复是自己发的，则不能回复，直接 删除/复制
				int userId = AppContext.getInstance().getMyUserId();
				if(item.fromUserId == userId){
					new AlertDialog.Builder(mContext)
					.setItems(new String[]{"复制","删除"}, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(which == 0){
								//复制								
								ClipboardManager cmb = (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE);
								ClipData clip = ClipData.newPlainText(item.getFromUserName(),item.reply);
								cmb.setPrimaryClip(clip); 
								Toast.makeText(mContext, "已复制", Toast.LENGTH_SHORT).show();
							} else if(which == 1){
								//删除
								deleteReply(position,item.id);
							}
						}
					})
					.create()
					.show();
					return;
				}
				//传入用户名和Id到评论框
				DialogReplyComment dialog = new DialogReplyComment(mContext);
				dialog.setReplyToComment(mCommentId,item.fromUserId,item.getFromUserName(),false);
				dialog.setOnReplaySuccessListener(new DialogReplyComment.OnReplaySuccessListener() {

					@Override
					public void onReplay(JsonReplyResult result) {
						//item.replyCount += 1;
						//将数据添加到数据集
						mData.add(result.reply);
						notifyDataSetChanged();
						//
						if(mOnAddListener != null){
							mOnAddListener.onAdd(true);
						}
					}
				});
				if(AppContext.getInstance().isLogin()) {
					dialog.show();
				} else {
					Intent intent = new Intent(mContext, ActivityLogin.class);
					mContext.startActivity(intent);
				}
			}
		});
		//长按
		hold.mLayout.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				new AlertDialog.Builder(mContext)
				.setItems(new String[]{"复制"}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0){
							//复制								
							ClipboardManager cmb = (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE);
							ClipData clip = ClipData.newPlainText(item.getFromUserName(),item.reply);
							cmb.setPrimaryClip(clip); 
							Toast.makeText(mContext, "已复制", Toast.LENGTH_SHORT).show();
						}
					}
				})
				.create()
				.show();
				return false;
			}
		});
	}
	
	/**
	 * 
	 * @param position 被删除数据 在数据集中的位置
	 * @param replyId 被删除数据 在服务器的id
	 */
	private void deleteReply(final int position,int replyId){
		showProgressDialog();
		mRequest = APIForPoint.deleteReply(replyId, new EHttpResponse() {
			
			@Override
			public void onEResponse(String response) {
				JsonBase result = GsonUtils.toBean(JsonBase.class, response);
				if(BaseActivity.handleResponseStatus(mContext, result)){
					//删除成功后，刷新
					mData.remove(position);
					notifyDataSetChanged();	
					if(mOnDeleteListener != null){
						mOnDeleteListener.onDelete(true);
					}
				}				
			}

			@Override
			public void onEErrorResponse(VolleyError error) {
				Toast.makeText(mContext, "错误：服务器返回数据失败！", Toast.LENGTH_SHORT).show();
				if(mOnDeleteListener != null){
					mOnDeleteListener.onDelete(false);
				}
			}

			@Override
			public void onEFinish() {
				// TODO Auto-generated method stub
				super.onEFinish();
				dismissProgressDialog();
			}			
			
		});
	}
		
	@Override
	public void notifyDataSetChanged() {
		// TODO Auto-generated method stub
		super.notifyDataSetChanged();
		
		
	}

	private void showProgressDialog(){
		dismissProgressDialog();
		mDialog = ProgressDialog.show(mContext, null, "提交中...", true, true, new DialogInterface.OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				if(mRequest != null){
					mRequest.cancel();
				}
			}
		});
		mDialog.setCanceledOnTouchOutside(false);
	}
	
	private void dismissProgressDialog(){
		if(mDialog != null && mDialog.isShowing()){
			mDialog.dismiss();
		}
	}

	public void setmOnDeleteListener(OnDeleteListener mOnDeleteListener) {
		this.mOnDeleteListener = mOnDeleteListener;
	}
	
	public void setmOnAddListener(OnAddListener mOnAddListener) {
		this.mOnAddListener = mOnAddListener;
	}

	public interface OnDeleteListener{
		public void onDelete(boolean result);
	}
	
	public interface OnAddListener {
		public void onAdd(boolean result);
	}

	/**
	 * 直接回复评论人的模板
	 */
	public final static String STR_1 = "<font color='#576b95'>%s</font>：%s";
	/**
	 * 回复评论回复 的模板
	 */
	public final static String STR_2 = "<font color='#576b95'>%s</font> " + 
			"<font color='#999999'>回复</font> " + 
			"<font color='#576b95'>%s</font>：%s";

}
